package com.zone.mybatis.executor;

import com.zone.mybatis.mapping.MappedStatement;
import com.zone.mybatis.session.Configuration;
import com.zone.mybatis.transaction.Transaction;

import java.sql.SQLException;
import java.util.List;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2024/1/1
 */
public abstract class BaseExecutor implements Executor {
    private boolean close;
    private final Configuration configuration;
    private final Transaction transaction;

    public BaseExecutor(Configuration configuration, Transaction transaction) {
        this.configuration = configuration;
        this.transaction = transaction;
    }

    @Override
    public <T> List<T> query(MappedStatement ms, Object paramObject) {
        if (close) {
            throw new RuntimeException("executor already close");
        }
        return this.doQuery(ms, paramObject);
    }

    public abstract <T> List<T> doQuery(MappedStatement ms, Object paramObject);

    @Override
    public Transaction getTransaction() {
        if (close) {
            throw new RuntimeException("executor already close");
        }
        return transaction;
    }

    @Override
    public void commit() throws SQLException {
        if (!close) {
            transaction.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if (!close) {
            transaction.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if (!close) {
            this.rollback();
            transaction.close();
            this.close = true;
        }
    }

    protected Configuration getConfiguration() {
        return this.configuration;
    }
}
